package com.siae.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siae.mapper.UserMapper;
import com.siae.pojo.User;
import com.siae.pojo.vo.Result;
import com.siae.service.UniversityService;
import com.siae.service.UserService;
import com.siae.utils.BizCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.net.InetAddress;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UniversityService universityService;

    @Override
    public Result<List<User>> findAllUser(Integer roleId) {
        try{
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq(roleId != null && roleId != 0,"role_id",roleId);
            List<User> list = userMapper.selectList(wrapper);
            return Result.success(BizCode.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询用户列表失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    /**
     * 登录验证
     * */
    @Override
    public Result<User> findAP(String account, String password) {
        try{
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("account",account);
            User user = userMapper.selectOne(wrapper);
            if (user.getId() != null){
                StringBuilder sb = new StringBuilder(SecureUtil.md5(password));
                String padS = SecureUtil.md5(sb.reverse().toString());
                Integer fAttempts = user.getFailedAttempts();
                // 判断登录次数
                if (fAttempts < 5){
                    // 判断密码是否正确
                    if (user.getPassword().equals(padS)){
                        user.setFailedAttempts(0);
                        user.setLockedUntil(null);
                        updateUser(user);
                        return Result.success(BizCode.SUCCESS,user);
                    } else {
                        fAttempts += 1;
                        user.setFailedAttempts(fAttempts);
                        // 当登录次数为5时，锁定账号，添加锁定时间
                        if (fAttempts == 5){
                            long lockedUntilTime = new Date().getTime();
                            lockedUntilTime += 30000;
                            user.setLockedUntil(String.valueOf(lockedUntilTime));
                        }
                        updateUser(user);
                        return Result.fail("用户名或密码错误,还有"+(5-fAttempts)+"次机会",null);
                    }
                } else {
                    long newTime = new Date().getTime();
                    long lastTime = Long.parseLong(user.getLockedUntil());
                    // 判断是否在锁定时间内
                    if (user.getLockedUntil() != null && newTime < lastTime){
                        long time = (lastTime - newTime) / 1000;
                        user.setLockedUntil(String.valueOf(time));
                        return Result.fail("用户登录次数超过上限,请在"+time+"秒后重试",null);
                    } else {
                        user.setFailedAttempts(0);
                        user.setLockedUntil(null);
                        updateUser(user);
                        findAP(account,password);
                    }
                }
            }
            return Result.fail(BizCode.USER_NOT_EXIST);
        }catch (Exception e){
            e.printStackTrace();
            log.error("登录验证失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result updatePwd(Map dateMap) {
        try {
            StringBuilder sb = new StringBuilder(SecureUtil.md5(dateMap.get("password").toString()));
            String pwd = SecureUtil.md5(sb.reverse().toString());
            User user = userMapper.selectById(dateMap.get("id").toString());
            if (user.getPassword().equals(pwd)){
                user.setPassword(SecureUtil.md5(SecureUtil.md5(dateMap.get("newPwd").toString())));
                userMapper.updateById(user);
                return Result.success(BizCode.SUCCESS);
            } else {
                return Result.fail(BizCode.INITIAL_PASSWORD_ERROR);
            }
        } catch (Exception e){
            e.printStackTrace();
            log.error("修改密码失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<User> getUserById(Integer id) {
        try{
            User user = userMapper.selectById(id);
            return Result.success(BizCode.SUCCESS,user);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询用户id失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<User> getUserByName(String name) {
        try{
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(name),"user_name",name);
            User user = userMapper.selectOne(wrapper);
            return Result.success(BizCode.SUCCESS,user);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询用户id失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result addUser(User user) {
        try {
            // 密码加密
            StringBuilder sb = new StringBuilder(SecureUtil.md5(user.getPassword()));
            String password = SecureUtil.md5(sb.reverse().toString());
            user.setPassword(password);
            // 获取本地ip
            InetAddress localHost = InetAddress.getLocalHost();
            user.setLastIp(localHost.toString().split("/")[1]);
            user.setAddTime(new Date());
            user.setUpdateTime(new Date());
            user.setFailedAttempts(0);
            user.setIsDel(0);
            int i = userMapper.insert(user);
            if (i > 0) {
                return Result.success(BizCode.SUCCESS);
            }
            return Result.fail(BizCode.FAIL);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("添加用户失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }
    }

    @Override
    public Result<User> updateUser(User user) {
        try {
            int i = userMapper.updateById(user);
            if(i > 0){
                return Result.success(BizCode.SUCCESS);
            }
            return Result.fail(BizCode.FAIL);
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改用户失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }

    }

    @Override
    public Result deleteUserById(Integer id) {
        try{
            User user = userMapper.selectById(id);
            user.setIsDel(1);
            int i = userMapper.deleteById(id);
            if(i > 0){
                return Result.success(BizCode.SUCCESS);
            }
            return Result.fail(BizCode.FAIL);
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除用户失败：{}",e.getMessage());
            return Result.fail(BizCode.SYSTEM_ERROR);
        }

    }
}